<template>
    <div class="app-container">
        <div class="table-info-row">
            <el-button class="back-btn" @click="handleClose">关闭</el-button>
        </div>
        <div class="content-box">
            <Bill :saleData="saleData" :payData="payData" :price="price" :vipPrice="vipPrice" :receive="receive"
                :received="received" :unpay="unpay" :tableInfo="tableInfo"  :vipInfo="vipInfo" :isVipPay="isVipPay" />
            <Payment :price="price" :vipPrice="vipPrice" :receive="receive" :received="received" :saleData="saleData"
                :payData="payData" :unpay="unpay" :tableInfo="tableInfo" :vipInfo="vipInfo" @emitSubmit="emitSubmit" />
        </div>
    </div>
</template>

<script setup >
import { formatDecimal } from '@/utils/chenhao'
// import Wares from './/wares.vue'
import Bill from './bill.vue'
import Payment from './payment.vue'
import Api from '@/api'
import ls from '@/lib/ls'
const router = useRouter()
const todo = router.currentRoute.value.query.todo
const serviceList = ref([])
if(router.currentRoute.value.query.serviceList){
    serviceList.value = JSON.parse(router.currentRoute.value.query.serviceList)
}

console.log(serviceList.value);

const vipInfo = ref({
    hasVipPrice: false,
    priceType: '1',
})

// 如果是换菜就把路由信息保存到缓存里，如果意外关闭就读取缓存
const ls_orderChange = ls.get('orderChange')
if (todo == 'orderChange') {
    if (!ls_orderChange) {
        let ls_orderChange_temp = {
            routerQuery: router.currentRoute.value.query,
            payData: [],
        }
        ls.set('orderChange', ls_orderChange_temp)
    }else{
        ElNotification({
            title: '提示',
            message: '上一次换菜收款因意外关闭，已还原关闭前的信息',
            type: 'success',
        })
    }
}


// -----------------------------------todo换菜功能------------------------------
// -------------------------------未结账商品模块-------------------------
// 商品列表
let tableInfo = ref()
if (todo == 'orderChange' || todo == 'mountPay') {
    tableInfo.value = {
        consumeCode: router.currentRoute.value.query.consumeCode,
        roomCode: router.currentRoute.value.query.roomCode,
        payBatchCode: router.currentRoute.value.query.payBatchCode,
    }
}


// -------------------------------应付金额模块-------------------------

// 优惠项目列表
let saleData = ref([])
if(serviceList.value){
    console.log(serviceList.value);
    serviceList.value.map((e)=>{
        e.je = e.amt
        e.yhxm = e.type
    })
    saleData.value = serviceList.value
    
}

const isVipPay = ref(router.currentRoute.value.query.isVip)
console.log(router.currentRoute.value.query);
// // 如果是权益会员付款的单换菜，自动加上会员优惠
if(isVipPay.value == '1'){
    let toolPrice = router.currentRoute.value.query.price
    let toolVipPrice = router.currentRoute.value.query.vipPrice
    vipInfo.value.hasVipPrice = true
    vipInfo.value.priceType = '2'
    console.log(toolPrice);
    console.log(toolVipPrice);
    let flag = false
    saleData.value.forEach((item, $index) => {
        if (item.yhxm == '会员折扣优惠') {
            flag = true
        }
    });
    if (!flag) {
        const saleObj = {
            yhxm: '会员折扣优惠',
            je: Number(toolPrice) - Number(toolVipPrice),
            code: router.currentRoute.value.query.payBatchCode,
            amt: Number(toolPrice) - Number(toolVipPrice),
            type: '会员折扣优惠',
            subType: '',
        }
        if(Number(toolPrice) != Number(toolVipPrice)){
                saleData.value.push(saleObj)
            }
        // saleData.value.push(saleObj)
    } 
}
// 支付方式列表
let payData = ref([])
if (ls_orderChange) {
    console.log('ls_orderChange.payData :>> ', ls_orderChange.payData);
    payData.value = ls_orderChange.payData
    console.log(ls_orderChange);
    isVipPay.value = ls_orderChange.routerQuery.isVip
    if(isVipPay.value == '1'){
    let toolPrice = router.currentRoute.value.query.price
    let toolVipPrice = router.currentRoute.value.query.vipPrice
    vipInfo.value.hasVipPrice = true
    vipInfo.value.priceType = '2'
    console.log(toolPrice);
    console.log(toolVipPrice);
    let flag = false
    saleData.value.forEach((item, $index) => {
        if (item.yhxm == '会员折扣优惠') {
            flag = true
        }
    });
        if (!flag) {
            const saleObj = {
                yhxm: '会员折扣优惠',
                je: Number(toolPrice) - Number(toolVipPrice),
                code: router.currentRoute.value.query.payBatchCode,
                amt: Number(toolPrice) - Number(toolVipPrice),
                type: '会员折扣优惠',
                subType: '',
            }
            if(Number(toolPrice) != Number(toolVipPrice)){
                saleData.value.push(saleObj)
            }
            
        } 
    }
    // payData.value= [{zffs:'111',skje:'222'}]
}


// --------------------------------------------计算属性---------------------------------------
// -------------------计算总价----------------
let routerPrice = router.currentRoute.value.query.price
const price = computed(() => {
    return routerPrice
})

// -------------------计算VIP价格----------------
let routerVipPrice = router.currentRoute.value.query.vipPrice
const vipPrice = computed(() => {
    return routerVipPrice
})

// ------------------计算应收------------------
const receive = computed(() => {
    let num = ""
    // console.log('num :>> ', num);
    if (vipInfo.value.priceType == '2') {
        num = vipPrice.value
    } else {
        num = price.value
    }
    saleData.value.forEach(item => {
        if (item.yhxm != '会员折扣优惠') {
            if (item.yhxm == '服务费' || item.yhxm == '补低消') {
                // 判断是服务费就加钱
                num = (+num) + (+item.je)
                // console.log('item.je :>> ', num + item.je);
            } else {
                // 其他就减
                num -= (+item.je)
            }
        }
    });
    return formatDecimal(num)
})
// ----------------计算已收------------------
const received = computed(() => {
    return payData.value.reduce((acc, cur) => {
        // console.log('acc :>> ', acc)
        // console.log('cur.skje :>> ', cur.skje)
        return formatDecimal((+acc) + (+cur.skje))
    }, '0')
})

// ----------------计算还需收款------------------
const unpay = computed(() => {
    return formatDecimal(receive.value - received.value) > 0 ? formatDecimal(receive.value - received.value) : '0'
})

// 子组件点击结账
const emitSubmit = () => {
    // getWaresData()
}

onUnmounted(() => {
    // window.removeEventListener('keydown', func1)
    ls.remove('WARES_ORDER')
    // ls.remove('payBatchCode')
})
// 点击关闭

const handleClose = (params) => {
    // 清除缓存
    ls.remove('orderChange')
    if (payData.value.length > 0) {
        if (todo == 'orderChange') {
            orderChange()
        }
        else if (todo == 'vipUpgrade') {
            vipUpgrade()
        } else if (todo == 'mountPay') {
            router.back()
        }
    } else {
        router.back()
    }
}

// 换菜
const orderChange = (params) => {
    let payItemCodes = payData.value.map(item => {
        // console.log('item :>> ', item);
        return item.itemCode
    })
    let data = {
        consumeCode: router.currentRoute.value.query.consumeCode,
        payBatchCode: router.currentRoute.value.query.payBatchCode,
        payItemCodes: payItemCodes.join(','),
    }
    Api.Common.PcObjProcess.Do({ "functionName": "OrderChangePayClose", "orgCode": "0004", "contentData": data }).then(res => {
        console.log('点击关闭 撤销所有订单 res :>> ', res);
        router.back()
    })
}

// 会员升级
const vipUpgrade = (params) => {
    let payItemCodes = payData.value.map(item => {
        // console.log('item :>> ', item);
        return item.itemCode
    })
    let data = {
        itemCodes: payItemCodes.join(','),
    }
    // console.log('会员升级 data :>> ', data);
    Api.Common.PcObjProcess.Do({ "functionName": "MemberUpPayRet", "contentData": data })
        .then(res => {
            console.log('会员升级取消 res :>> ', res);
            router.back()
        })
}


// 阻止F5刷新
// const handleKeydown = (e) => {
//     if (e.key === "F5") {
//         e.preventDefault();
//     }
// };
// onMounted(() => {
//     window.addEventListener("keydown", handleKeydown, false);
// });

// onUnmounted(() => {
//     window.removeEventListener("keydown", handleKeydown, false);
// });
</script>

<style scoped lang="scss">
/* 在这里编写组件的CSS样式 */
.app-container {
    height: 100%;
    padding: 20px 100px 0px 100px;
    background: #F2F2F2;

    .table-info-row {
        width: 100%;
        display: flex;
        // justify-content: space-between;
        justify-content: end;

        .table-info {
            width: 1540px;
            height: 60px;
            background: #FFFFFF;
            border-radius: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 39px;
        }

        .back-btn {
            width: 120px;
            height: 60px;
            background: #CCCCCC;
            border-radius: 8px;
            font-size: 18px;
            color: #212121;
            border: 0px;
        }
    }

    .content-box {
        margin-top: 20px;
        display: flex;
        justify-content: center;
    }
}

.font-size-16 {
    font-size: 16px;
}

.font-size-20 {
    font-size: 20px;
}

.font-weight-blod {
    font-weight: bold;
}

.font-weight-normal {
    font-weight: normal;
}

.color-212121 {
    color: #212121;
}

.color-FF3333 {
    color: #FF3333;
}
</style>
